package main;

import model.SimpleGoL;
import thread.Thread1;
import util.Utils;

import java.io.*;
import java.util.concurrent.*;

/**
 * @author Xu,
 * @data 2020/11/11，
 * @time 18:57
 * 主函数增加2个子线程，一个跑左棋盘，一个跑右棋盘
 * size分解，0~size/2+1,size/2+1~size
 */
public class Main {
    private static SimpleGoL simpleGoL;
    private static int size;
    private static int day;
    private static int i;
    public static void main(String[] args) throws Exception {
        long start = System.currentTimeMillis();
        seachForTxt();
        long end1 = System.currentTimeMillis();
        System.out.println("search runtime: " + (end1 - start)/1000+"s");
        /**
         * 主线程调用两个子线程，
         * 子线程跑左右两边棋盘，主线程加join等待子线程跑完；
         * 主线程再次调用子线程；
         * 更新：
         * 显式创建线程不好，尽量使用线程池。
         * 用继承Thread类的方法只能分为两个子线程，4个或8个会报错：Java heap space
         * 创建和销毁线程上所花的时间以及系统资源的开销大，资源不足
         *
         * 线程池学不来
         */
        Thread t = new Thread(()->{
            while(day != 0){
                System.out.println("正在执行生命游戏第" + (1001-day) + "次转变");
                Thread t1 = new Thread1(0,size/2);
                Thread t2 = new Thread1(size/2,size);
                t1.start();
                t2.start();
                try {
                    t1.join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                day--;
            }
        });
        t.start();
        t.join();
//        CountDownLatch count = new CountDownLatch(day*2);
//        ExecutorService executorService = new ThreadPoolExecutor(2, 2, 0L,
//                TimeUnit.MILLISECONDS,
//                new LinkedBlockingQueue<>(10),
//                Executors.defaultThreadFactory(),
//                new ThreadPoolExecutor.AbortPolicy());
//
//        for (i = 1; i < 3; i++) {
//            executorService.execute(new Runnable() {
//                int day1 = day;
//                @Override
//                public void run() {
//                    while(day1 != 0){
//
//                        day1--;
//                        count.countDown();
//                        try {
//                            Thread.sleep(0,1);
//                        } catch (InterruptedException e) {
//                            e.printStackTrace();
//                        }
//                    }
//                }
//            });
//        }
//        count.await();
//        executorService.shutdown();
        createTable();
        long end = System.currentTimeMillis();
        System.out.println("runtime: " + (end - start)/1000+"s");
    }




    /**
     * 查找input.txt文件并读取size，day
     * @throws IOException
     */
    public static void seachForTxt() throws IOException {
        String filepath = "./src/in_10000.txt";
        simpleGoL = Utils.initMapFromFile(filepath);
        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(filepath)));
        String[] array = reader.readLine().split(" ");
        size = Integer.parseInt(array[0]);
        System.out.println(size);
        String line1 = reader.readLine();
        String[] array1 = line1.split(" ");
        day = Integer.parseInt(array1[0]);
        System.out.println(day);
    }

    /**
     * 生成.txt文件
     */
    public static void createTable() {
        String path = "./src/output.txt";
        BufferedOutputStream bufferedOutputStream = null;
        FileOutputStream outputStream = null;
        StringBuffer stringBuffer;
        try {
            outputStream = new FileOutputStream(new File(path));
            bufferedOutputStream = new BufferedOutputStream(outputStream);
            for (int i = 0; i < size; i++) {
                for (int j = 0; j < size; j++) {
                    if (simpleGoL.getMap()[i][j] == 1) {
                        stringBuffer = new StringBuffer();
                        stringBuffer.append(i + "," + j + "\n");
                        bufferedOutputStream.write(stringBuffer.toString().getBytes("UTF-8"));
                    }
                }
            }
            bufferedOutputStream.flush();
            bufferedOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                bufferedOutputStream.close();
                outputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


        for (int i = 0; i < size; i++) {
            for (int j = 0; j < size; j++) {
                if (simpleGoL.getMap()[i][j] == 1) {
                    System.out.println(i + "," + j);
                }
            }
        }

        /**
         * 遍历查看结果
         */
//        for(int i=0; i<size; i++){
//            for(int j=0; j<size; j++){
//                System.out.print(simpleGoL.getMap()[i][j] + " ");
//            }
//            System.out.println();
//        }
    }

    public static SimpleGoL getSimpleGoL() {
        return simpleGoL;
    }

    public static int getSize() {
        return size;
    }

    public static int getDay() {
        return day;
    }
}
